package com.ljj.examisto.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SwitchCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.ljj.examisto.R
import com.ljj.examisto.data.adapter.SettingAdapter
import com.ljj.examisto.data.item.SettingBlock
import com.ljj.examisto.data.item.SettingOption
import com.ljj.examisto.databinding.ActivitySettingBinding
import com.ljj.examisto.util.Logger.TAG
import com.ljj.examisto.util.ToastManager
import kotlin.properties.Delegates

class SettingActivity : AppCompatActivity() {
    companion object {
        // 闹钟型提醒自动关闭时间参数（单位：秒）
        private const val MIN_TIME = 1
        private const val MAX_TIME = 3600
        private const val DEFAULT_TIME = 300
    }
    private lateinit var binding: ActivitySettingBinding
    private lateinit var settingAdapter: SettingAdapter
    private lateinit var prefs: SharedPreferences
    private lateinit var keyIs24HourFormat: String
    private var is24HourFormat by Delegates.notNull<Boolean>()
    private lateinit var keyAutomaticallyShutdownTime: String
    private var automaticallyShutdownTime by Delegates.notNull<Int>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initProperty()
        setupViews()
    }

    /* 流程函数 */
    private fun initProperty() {
        binding = ActivitySettingBinding.inflate(layoutInflater)
        prefs = getSharedPreferences(getString(R.string.app_preference_name), Context.MODE_PRIVATE)
        keyIs24HourFormat = getString(R.string.key_is_24_hour_format)
        is24HourFormat = prefs.getBoolean(keyIs24HourFormat, true)
        keyAutomaticallyShutdownTime = getString(R.string.key_automatically_shutdown_time)
        automaticallyShutdownTime = prefs.getInt(keyAutomaticallyShutdownTime, DEFAULT_TIME)
    }

    private fun setupViews() {
        setContentView(binding.root)
        setupSettingView()
        setListeners()
    }

    private fun setupSettingView() {
        val settingBlocks: List<SettingBlock> = getSettings()
        settingAdapter = SettingAdapter(settingBlocks)
        binding.rcvSetting.layoutManager = LinearLayoutManager(this)
        binding.rcvSetting.adapter = settingAdapter
    }

    private fun setListeners() {
        setupBackButton()
        setupSaveButton()
        setupTimeFormatSwitch()
        setupAutomaticallyShutdownTimeEditText()
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun setupBackButton() {
        binding.btnBack.setOnTouchListener { view, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    binding.btnBack.setBackgroundResource(R.drawable.ic_back_pressed)
                    true
                }
                MotionEvent.ACTION_MOVE -> {
                    if (!isTouchInsideView(view, event)) {
                        binding.btnBack.setBackgroundResource(R.drawable.ic_back)
                    }
                    true
                }
                MotionEvent.ACTION_UP -> {
                    binding.btnBack.setBackgroundResource(R.drawable.ic_back)
                    if (isTouchInsideView(view, event)) {
                        backToHome()
                    }
                    true
                }
                MotionEvent.ACTION_CANCEL -> {
                    binding.btnBack.setBackgroundResource(R.drawable.ic_back)
                    true
                }
                else -> false
            }
        }
    }

    private fun setupSaveButton() {
        binding.btnSave.setOnClickListener {
            prefs.edit().apply {
                // 保存各项设置数据
                putBoolean(keyIs24HourFormat, is24HourFormat)
                putInt(keyAutomaticallyShutdownTime, automaticallyShutdownTime)
                apply()
            }
            setIsEnabledForSaveButton(false)
            ToastManager.interruptedToast(this, "已保存", Toast.LENGTH_SHORT)
        }
    }

    private fun setupTimeFormatSwitch() {
        val timeFormatSwitch = settingAdapter.getWidget(getString(R.string.use_24_hour_format)) as? SwitchCompat
        val originalValue = is24HourFormat
        if (timeFormatSwitch != null) {
            // 初始化控件表现
            timeFormatSwitch.isChecked = is24HourFormat
        } else {
            Log.d(TAG, "时制开关不存在！")
            return
        }
        timeFormatSwitch.setOnCheckedChangeListener { _, isChecked ->
            when (isChecked) {
                true -> ToastManager.interruptedToast(this, "24小时制", Toast.LENGTH_SHORT)
                false -> ToastManager.interruptedToast(this, "12小时制", Toast.LENGTH_SHORT)
            }
            if (isChecked != originalValue) {
                is24HourFormat = isChecked
                setIsEnabledForSaveButton(true)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun setupAutomaticallyShutdownTimeEditText() {
        val automaticallyShutdownTimeEditText = settingAdapter.getWidget(getString(R.string.alarm_reminder_automatically_shutdown_time)) as? EditText
        if (automaticallyShutdownTimeEditText != null) {
            automaticallyShutdownTimeEditText.setText(automaticallyShutdownTime.toString())
        } else {
            Log.d(TAG, "自动关闭闹钟时间输入框不存在！")
            return
        }
        automaticallyShutdownTimeEditText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                var time = s.toString().toIntOrNull()
                when {
                    time == null -> {
                        setIsEnabledForSaveButton(false)
                    }
                    time < MIN_TIME -> {
                        time = MIN_TIME
                        automaticallyShutdownTimeEditText.setText(time.toString())
                        automaticallyShutdownTime = time
                        setIsEnabledForSaveButton(true)
                        ToastManager.interruptedToast(this@SettingActivity, "最小值为${MIN_TIME}秒", Toast.LENGTH_SHORT)
                    }
                    time > MAX_TIME -> {
                        time = MAX_TIME
                        automaticallyShutdownTimeEditText.setText(time.toString())
                        automaticallyShutdownTime = time
                        setIsEnabledForSaveButton(true)
                        ToastManager.interruptedToast(this@SettingActivity, "最大值为${MAX_TIME}秒", Toast.LENGTH_SHORT)
                    }
                    else -> {
                        automaticallyShutdownTime = time
                        setIsEnabledForSaveButton(true)
                    }
                }
            }
        })
    }

    /* 工具函数 */
    private fun isTouchInsideView(view: View, event: MotionEvent): Boolean {
        val x = event.x
        val y = event.y
        return x >= 0 && x <= view.width && y >= 0 && y <= view.height
    }

    private fun backToHome() {
        startActivity(Intent(this, HomeActivity::class.java))
        finish()
    }

    private fun getSettings(): List<SettingBlock> {
        // 时间类Option列表
        val settingOptionsAboutTime = listOf(
            SettingOption(getString(R.string.use_24_hour_format), SwitchCompat(this)),
            SettingOption(getString(R.string.alarm_reminder_automatically_shutdown_time), EditText(this).apply {
                inputType = InputType.TYPE_CLASS_NUMBER
                hint = "$MIN_TIME~$MAX_TIME"
            })
        )
        // Block列表
        val settingBlocks = listOf(
            SettingBlock("时间", settingOptionsAboutTime)
        )
        return settingBlocks
    }

    private fun setIsEnabledForSaveButton(isEnabled: Boolean) {
        when (isEnabled) {
            true -> {
                binding.btnSave.alpha = 1f
                binding.btnSave.isEnabled = true
            }
            false -> {
                binding.btnSave.alpha = 0.5f
                binding.btnSave.isEnabled = false
            }
        }
    }
}